<template>
	<div>
		<div class="container">
			<div class="toolbar">
				<a-form ref="searchRef" :model="searchState" :label-col="{style: { width: '80px' }}" @finish="current=1;initData()">
					<a-row :gutter="22">
						<a-col :span="4">
							<a-form-item label="材料分类">
								<a-tree-select v-model:value="searchState.source_id" :show-search="true" placeholder="请选择物资名称" allow-clear tree-default-expand-all :tree-data="materialOptions" tree-node-filter-prop="label" style="width:100%" @change="(id)=>changeSearchMaterial(id)">
									<template #title="{label}">{{ label }}</template>
								</a-tree-select>
							</a-form-item>
						</a-col>
						<a-col :span="4">
							<a-form-item label="规格型号">
								<a-select v-model:value="searchState.material_id" :show-search="true" option-filter-prop="model" placeholder="请选择" :options="materialSearchModelOptions[searchState.source_id] || []" allow-clear :field-names="{value:'id', label:'model'}" style="width:100%"></a-select>
							</a-form-item>
						</a-col>
						<a-col :span="6">
							<a-form-item label="计价方式">
								<a-radio-group v-model:value="searchState.price_type">
									<a-radio :value="1">月浮动</a-radio>
									<a-radio :value="2">日浮动</a-radio>
								</a-radio-group>
							</a-form-item>
						</a-col>
						<a-col :span="4">
							<a-form-item label="关键词">
								<a-input v-model:value="searchState.code" placeholder="请输入" allow-clear></a-input>
							</a-form-item>
						</a-col>
						<!--
						<a-col :span="4">
							<a-range-picker v-model:value="searchState.date_range" format="YYYY/MM/DD" value-format="YYYY-MM-DD" />
						</a-col>-->
						<a-col :span="4">
							<a-space>
								<a-button type="primary" html-type="submit">
									<search-outlined />搜索
								</a-button>
							</a-space>
						</a-col>
					</a-row>
				</a-form>
			</div>

			<div class="container mt-2">
				<div class="mb-2">
					<a-space>
						<a-button v-permission="84" type="primary" @click="addPrice">
							<plus-outlined />添加价格记录
						</a-button>
					</a-space>
				</div>
			</div>

			<div class="mt-2">
				<a-tabs v-model:activeKey="activeKey" @change="changeTab">
					<a-tab-pane key="1" tab="月浮动物资">
						<a-table v-if="!loading" :columns="columns" :scroll="tableScroll" row-key="id" children-column-name="children" :default-expand-all-rows="false" :data-source="priceSource" :pagination="pagination" :loading="loading" @change="initData">
							<template #bodyCell="{ column, record }">
								<template v-if="column.key === 'operation'">
									<a-space>
										<a-button v-permission="85" type="link" @click="editPrice(record)">
											<edit-outlined />设置价格
										</a-button>
										<a-button v-permission="86" type="link" @click="showPrice(record)">
											<snippets-outlined />查看历史价
										</a-button>
									</a-space>
								</template>
							</template>
						</a-table>
					</a-tab-pane>
					<a-tab-pane key="2" tab="日浮动物资">
						<a-table v-if="!loading" :columns="columns" :scroll="tableScroll" row-key="id" children-column-name="children" :default-expand-all-rows="false" :data-source="priceSource" :pagination="pagination" :loading="loading" @change="initData">
							<template #bodyCell="{ column, record }">
								<template v-if="column.key === 'operation'">
									<a-space>
										<a-button v-permission="85" type="link" @click="editPrice(record)">
											<edit-outlined />设置价格
										</a-button>
										<a-button v-permission="86" type="link" @click="showPrice(record)">
											<snippets-outlined />查看历史价
										</a-button>
									</a-space>
								</template>
							</template>
						</a-table>
					</a-tab-pane>
				</a-tabs>
			</div>
		</div>
		<a-modal v-model:visible="visible" :width="1000" :title="`${formState.id ? '修改' : '添加'}价格记录`" @ok="savePrice">
			<a-form ref="formRef" layout="horizontal" :model="formState" v-bind="{labelCol: { style: { width: '80px' } }}">
				<a-form-item label="物资名称" :name="source_id" :rules="{required:true, message:'请选择物资名称'}">
					<a-tree-select v-model:value="formState.source_id" :show-search="true" placeholder="请选择物资名称" allow-clear tree-default-expand-all :tree-data="materialOptions" tree-node-filter-prop="label" style="width:100%" @change="(id)=>changeMaterial(id)">
						<template #title="{label}">{{ label }}</template>
					</a-tree-select>
				</a-form-item>
				<a-form-item label="规格型号" :name="material_id" :rules="{required:true, message:'请选择规格'}">
					<a-select v-model:value="formState.material_id" :show-search="true" option-filter-prop="model" placeholder="请选择" :options="materialModelOptions[formState.source_id] || []" allow-clear :field-names="{value:'id', label:'model'}" style="width:100%"></a-select>
				</a-form-item>
				<a-form-item label="日期类型" name="price_type" :rules="{required:true, message:'请输入'}">
					<a-radio-group v-model:value="formState.price_type" @change="setPricetype">
						<a-radio :value="1">按月浮动</a-radio>
						<a-radio :value="2">按日浮动</a-radio>
					</a-radio-group>
				</a-form-item>
				<a-form-item label="选择日期" name="date" :rules="{required:true, message:'请输入'}">
					<a-date-picker v-model:value="formState.date" :picker="date_type" value-format="YYYY-MM-DD" />
				</a-form-item>
				<a-form-item label="价格" name="price" :rules="{required:true, message:'请输入'}">
					<a-input v-model:value="formState.price" />
				</a-form-item>
			</a-form>
		</a-modal>
		<a-modal v-model:visible="price_visible" :width="400" :title="`设置价格`" @ok="setPrice">
			<a-form ref="formRef1" :model="priceForm" v-bind="{labelCol: { style: { width: '80px' } }}">
				<a-form-item label="价格" name="price" :rules="{required:true, message:'请输入价格'}">
					<a-input v-model:value="priceForm.price" />
				</a-form-item>
			</a-form>
		</a-modal>
	</div>
</template>

<script setup>
import { computed, getCurrentInstance, reactive, ref, watch } from "vue";

const { proxy } = getCurrentInstance();
import dayjs from "dayjs";
import { PlusOutlined, SearchOutlined, SnippetsOutlined, EditOutlined } from "@ant-design/icons-vue";
import { post, listToTree } from "../utils";
import { usePagination } from "vue-request";
import { useRoute, useRouter } from "vue-router";

const searchState = reactive({});
const materialOptions = ref([]);
const date_type = ref();
const materialModelOptions = ref({});
const materialSearchModelOptions = ref({});
const route = useRoute();
const router = useRouter();
const query = route.query;
const setPricetype = value => {
	if (formState.value.price_type === 1) {
		date_type.value = "month";
	} else {
		date_type.value = "";
	}
};
const editPrice = record => {
	priceForm.value.price = record.price;
	priceForm.value.material_id = record.material_id;
	priceForm.value.price_type = record.price_type;
	price_visible.value = true;
};
const activeKey = ref("1");
post("dictionary", { root_code: "MATERIAL_CATEGORY", type: 1 }).then(data => {
	const { root_id: rootId } = data[0] || {};
	materialOptions.value = listToTree(data, rootId);

	//获取所有规格
	post("material", { source_id: data.map(d => d.id).join(","), page_size: 10000 }).then(({ data }) => {
		materialModelOptions.value = (() => {
			const array = [];
			data.forEach(d => {
				if (!array[d.source_id]) array[d.source_id] = [];

				if (d.attr) d.model = `${d.model}（${d.attr}）`;

				array[d.source_id].push(d);
			});

			return array;
		})(data);
	});
});
const changeMaterial = id => {
	//强制选择规格
	if (!id) return;
	post("material", { source_id: id, page_size: 10000 }).then(({ data }) => {
		materialModelOptions.value[id] = data.map(d => {
			if (d.attr) d.model = `${d.model}（${d.attr}）`;

			return d;
		});
	});
};
const changeSearchMaterial = id => {
	//强制选择规格
	if (!id) return;
	post("material", { source_id: id, page_size: 10000 }).then(({ data }) => {
		materialSearchModelOptions.value[id] = data.map(d => {
			if (d.attr) d.model = `${d.model}（${d.attr}）`;

			return d;
		});
	});
};
const columns = [
	{
		title: "序号",
		dataIndex: "id",
		key: "id",
		width: 80,
		align: "left",
		fixed: "left"
	},
	/**
	{
		title: "物资编号",
		dataIndex: "material",
		sorter: false,
		width: 150,
		ellipsis: true,
		fixed: "left",
		customRender: ({ text, record, index, column }) => {
			//未设置dataIndex，text和record返回值相同
			return text.code ? text.code : "";
		}
	}, */
	{
		title: "物资名称",
		dataIndex: "material",
		sorter: false,
		width: 150,
		ellipsis: true,
		fixed: "left",
		customRender: ({ text, record, index, column }) => {
			//未设置dataIndex，text和record返回值相同
			return text.name;
		}
	},
	{
		title: "规格型号",
		dataIndex: "material",
		sorter: false,
		width: 150,
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			//未设置dataIndex，text和record返回值相同
			return text.model;
		}
	},
	{
		title: "计量单位",
		dataIndex: "material",
		sorter: false,
		width: 150,
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			//未设置dataIndex，text和record返回值相同
			return text.unit;
		}
	},
	{
		title: "计价方式",
		dataIndex: "price_type",
		width: 150,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return text === 1 ? "月浮动" : "日浮动";
		}
	},
	{
		title: "价格",
		dataIndex: "price",
		sorter: false,
		width: 150,
		ellipsis: true
	},

	{
		title: "日期",
		dataIndex: "price_month",
		width: 150,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return dayjs(text).format("YYYY-MM-DD");
		}
	},
	{
		title: "操作员",
		dataIndex: "user",
		sorter: false,
		width: 150,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			//未设置dataIndex，text和record返回值相同
			return text.fullname;
		}
	},
	/**
	{
		title: "最后更新时间",
		dataIndex: "update_time",
		width: 150,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return dayjs(text).format("YYYY-MM-DD HH:mm:ss");
		}
	}, */
	{
		title: "操作",
		key: "operation",
		sorter: false,
		fixed: "right",
		width: 300,
		align: "center"
	}
];
const tableScroll = computed(() => ({ x: document.documentElement.clientWidth - 650 }));

const { data, loading, run, current, pageSize, total } = usePagination(params => post("price", { price_type: 1, ...params, ...searchState, date_range: JSON.stringify(searchState.date_range) }), {
	defaultParams: [
		{
			page_size: 10
		}
	],
	pagination: {
		currentKey: "page",
		pageSizeKey: "page_size",
		totalKey: "total"
	}
});

const priceSource = computed(() =>
	(data.value?.data || []).map(d => {
		if (d.children?.length === 0) delete d.children;
		return d;
	})
);
const changeTab = activeKey => {
	//searchState.price_type = activeKey;
	initData({}, { price_type: activeKey });
};

const pagination = computed(() => ({
	total: total.value,
	current: current.value,
	pageSize: pageSize.value
}));

const initData = (pag, filters, sorter) => {
	pag = Object.assign(
		{
			current: current.value,
			pageSize: pageSize.value
		},
		pag || {}
	);
	filters = { ...filters, ...searchState };
	const query = {};
	if (pag?.pageSize) {
		query['page_size'] = pag?.pageSize;
	}
	if (pag?.current) {
		query['page'] = pag?.current;
	}
	if (activeKey.value) {
		query['active_key'] = activeKey.value;
	}
	router.replace({ query: {
		...query,
		...filters
	}})
	run({
		page_size: pag?.pageSize,
		page: pag?.current,
		sort_field: sorter?.field,
		sort_order: sorter?.order,
		...filters
	});
};
if (query) {
	if (query.source_id) searchState.source_id = parseInt(query.source_id);
	if (query.material_id) searchState.material_id = parseInt(query.material_id);
	if (query.price_type) searchState.price_type = parseInt(query.price_type);
	if (query.code) searchState.code = query.code;
	if (query.active_key) activeKey.value = query.active_key;
	const pag = {};
	if (query.page) {
		pag['current'] = parseInt(query.page);
	}
	if (query.pageSize) {
		pag['pageSize'] = parseInt(query.page_size);
	}
	initData(pag);
}
const visible = ref(false);
const formState = ref({});
const price_visible = ref(false);
const priceForm = ref({});
const addPrice = () => {
	visible.value = true;
};

const showPrice = record => {
	const material_id = record.material_id;
	router.push(`price/log?material_id=${material_id}`);
};
const formRef = ref();
const formRef1 = ref();
const savePrice = () => {
	formRef.value
		.validate()
		.then(() => {
			proxy.$message.destroy();

			const params = { ...formState.value };

			post("price/save", params)
				.then(() => {
					proxy.$message.success("提交成功", 1);
					initData();
					visible.value = false;
				})
				.catch(err => {
					proxy.$message.error(err);
				});
		})
		.catch(err => {});
	initData();
};
const setPrice = () => {
	formRef1.value
		.validate()
		.then(() => {
			proxy.$message.destroy();

			const params = { ...priceForm.value };
			post("price/save", params)
				.then(() => {
					proxy.$message.success("提交成功", 1);
					initData();
					price_visible.value = false;
				})
				.catch(err => {
					proxy.$message.error(err);
				});
		})
		.catch(err => {});
	activeKey.value = "1";
	initData();
};
watch(visible, value => {
	if (value) formRef.value?.clearValidate();
});
</script>
<style scoped lang="scss">
.container {
	background: #fff;
	padding: 12px;
}
:deep(.ant-input[disabled]) {
	color: rgba(0, 0, 0, 0.65);
	background: #fff;
	border: 1px solid #d9d9d9;
}
:deep(.ant-input-disabled) {
	color: rgba(0, 0, 0, 0.65);
	background: #fff;
	border: 1px solid #d9d9d9;
}
</style>